import React, { useState } from 'react'
import { fromNowFun } from '@/utils'
import { tagList } from '@/utils/data'
import api from '@/api'
import Model from '@/pages/components/model'
export default function BlogList(props) {
    const { list } = props;
    const userDataStr = window.localStorage.getItem('userData')
    const userData = userDataStr ? JSON.parse(userDataStr) : {}
    const [isOpen, setIsOpen] = useState(false)
    const [username, setUsername] = useState('')
    const [password, setPassword] = useState('')
    const [num, setNum] = useState(0)

    // 展示列表
    // 上拉加载
    // 点击进入详情
    // 支持点赞
    const getTabNameById = (id) => {
        let title = ''
        tagList.forEach(item => {
            if (item.id === id) {
                title = item.name
            } else if (item.children) {
                item.children.forEach(item2 => {
                    if (item2.id === id) {
                        title = item2.name;
                    }
                })
            }
        })
        return title;
    }
    // 点赞
    const likeFun = (id: number, item: any) => {
        api.like({
            "user_id": userData.id,
            "blog_id": id
        }).then((res: any) => {
            if (res.success) {
                // 涉及到性能优化 
                // 调完点赞接口 页面视图没有更新 所以这里手动更新
                item.isLike = !item.isLike;
                item.isLike ? item.likes += 1 : item.likes -= 1
                // 只修改数据的话 视图无法触发更新 因为react不是响应式的
                setNum(prev => prev += 1) // 所以需要手动触发更新
            }
        }, (err: any) => {
            if (err.response.status === 401) {
                setIsOpen(true)
            }
        })
    }
    // 登录
    const loginFun = () => {
        api.login({ username, password }).then((res: any) => {
            if (res.success) {
                window.localStorage.setItem('token', res.data.token)
                window.localStorage.setItem('userData', JSON.stringify(res.data.userData))
            }
        })
    }
    return (
        <div className="home_list">
            {list.map((item: any) => {
                return <div className="list_item" key={item.id} onClick={() => {
                    props.history.push('/detail/' + item.id)
                }}>
                    <div className="left_item">
                        <div className="top_item">
                            <span className="author">{item.author}</span>
                            <span className="date">{fromNowFun(item.create_time)}</span>
                            <span className="tag">{getTabNameById(item.type)}</span>
                        </div>
                        <div className="center_item">{item.title}</div>
                        <div className="bottom_item">{item.content}</div>
                        <div className="action_item">
                            <span>浏览量：{item.looks}</span>
                            <span>评论数：{item.comments}</span>
                            {/* 如果true 说明赞过了 显示取消点赞 */}
                            {!item.isLike ? <button onClick={(e) => {
                                likeFun(item.id, item)
                                e.stopPropagation()
                            }}>点赞{item.likes}</button> :
                                <button onClick={(e) => {
                                    likeFun(item.id, item)
                                    e.stopPropagation() // 阻止冒泡
                                }}>取消点赞{item.likes}</button>}
                        </div>
                    </div>
                    <div className="right_item">
                        <img src={item.image} alt="" />
                    </div>
                </div>
            })}
            <Model isOpen={isOpen} title={'请登录'} success={() => {
                loginFun()
            }} cancel={() => {
                setIsOpen(false)
            }}>
                <form>
                    账号 <input type="text" value={username} onChange={({ target: { value } }) => { setUsername(value) }} />
                    <br />
                    密码 <input type="password" value={password} onChange={({ target: { value } }) => { setPassword(value) }} />
                    <br />
                </form>
            </Model>
        </div>
    )
}
